package com.payment.web.controller.app;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.payment.common.base.AjaxResult;
import com.payment.common.type.ResourcesTypeStatus;
import com.payment.common.utils.DateUtils;
import com.payment.common.utils.RedisPoolUtil;
import com.payment.common.utils.StringUtils;
import com.payment.system.domain.Merchant;
import com.payment.system.domain.MoneyChange;
import com.payment.system.domain.PaymentOrder;
import com.payment.system.domain.SystemConfig;
import com.payment.system.service.IAnnouncementService;
import com.payment.system.service.IMerchantService;
import com.payment.system.service.IMoneyChangeService;
import com.payment.system.service.IPaymentOrderService;
import com.payment.system.service.IResourcesDataService;
import com.payment.system.service.IResourcesTypeService;
import com.payment.system.service.ISystemConfigService;

/**
 * @author fuzhili
 * @Description: 图文资源处理 轮播图 178学堂
 * @date 2019/1/13 10:10
 */
@Controller
@RequestMapping("/app/resources")
public class ResourcesController {
	@Autowired
	private IResourcesDataService resourcesDataService;
	@Autowired
	private IResourcesTypeService resourcesTypeService;
	@Autowired
	private IAnnouncementService announcementService;
	@Autowired
	private IMerchantService merchantService;
	@Autowired
	private IPaymentOrderService paymentOrderService;
	@Autowired
	private ISystemConfigService configService;
	@Autowired
	private IMoneyChangeService moneyChangeService;

	/**
	 * 获取轮播图或者分享图片
	 *
	 * @param type
	 *            20A:轮播图 60A办卡贷款连接
	 * @return
	 */
	@RequestMapping("/advertList")
	@ResponseBody
	public AjaxResult advertList(String type) {
		if (StringUtils.isEmpty(type)) {
			return AjaxResult.error(1, "缺失参数");
		}
		if (StringUtils.equals(type, ResourcesTypeStatus.LA.getCode())) {
			// 轮播图
			type = ResourcesTypeStatus.LA.getCode();
		} else if (StringUtils.equals(type, ResourcesTypeStatus.DK.getCode())) {
			// 贷款连接路径
			type = ResourcesTypeStatus.DK.getCode();
		} else if (StringUtils.equals(type, ResourcesTypeStatus.C.getCode())) {
			// 推广素材
			type = ResourcesTypeStatus.C.getCode();
		} else if (StringUtils.equals(type, ResourcesTypeStatus.B.getCode())) {
			type = ResourcesTypeStatus.B.getCode();
		} else if (StringUtils.equals(type, ResourcesTypeStatus.G.getCode())) {
			type = ResourcesTypeStatus.G.getCode();
		} else if (StringUtils.equals(type, ResourcesTypeStatus.H.getCode())) {
			type = ResourcesTypeStatus.H.getCode();
		} else if (StringUtils.equals(type, ResourcesTypeStatus.LB.getCode())) {
			type = ResourcesTypeStatus.LB.getCode();
		} else {
			return AjaxResult.error(2, "暂不支持此类型");
		}
		return resourcesDataService.selectResourcesDataByType(type);
	}

	/**
	 * app端 公告列表 type:0 ios,1 安卓
	 * 	 *
	 * @param merchantId
	 * @param type
	 * @return
	 */
	@RequestMapping("/announcemenList")
	@ResponseBody
	public AjaxResult announcemenList(String merchantId, Integer type) {
		return announcementService.selectAnnouncementListByApp(merchantId, type);
	}
	/**
	 * 待删除
	 * @param merchantId
	 * @return
	 */
	@RequestMapping("/tryVipContext")
	@ResponseBody
	public AjaxResult tryVipContext(String merchantId) {
		return AjaxResult.error();
	}
	/**
	 * app端 	 首页公告
	 * @param merchantId
	 * @return
	 */
	@RequestMapping("/getIndexNotice")
	@ResponseBody
	public AjaxResult getIndexNotice(String merchantId) {
		List<Map<String, Object>> li = new ArrayList<Map<String, Object>>();
		String commission = "";
        try {
            commission = RedisPoolUtil.get("commission");
        } catch (Exception e) {
            commission = "nil";
        }
        if (commission == null || "nil".equals(commission)) {
            SystemConfig config = configService.selectSystemConfigByConfigCode("commission");
            RedisPoolUtil.setex("commission", config.getConfigValue(), 86400);
            commission = config.getConfigValue();
        }
        JSONObject jsonConfig = JSONObject.parseObject(commission);
        boolean isTryVip = jsonConfig.getBooleanValue("isTryVip");
		Merchant merchant = merchantService.selectMerchantById(merchantId);
		if (isTryVip && merchant.getLevel().equals(1)) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(merchant.getRealNameTime());
			calendar.add(Calendar.MONTH, 2);
			if (calendar.getTime().compareTo(new Date()) == -1 && DateUtils.compareDateDay(calendar.getTime()) <= 7) {
				Map<String, Object> map = new HashMap<>();
				map.put("context", getTryVipContext(merchantId, calendar, 1));
				map.put("type", "vip");
				li.add(map);
			} else if (calendar.getTime().compareTo(new Date()) >= 0 && DateUtils.compareDateDay(calendar.getTime()) >=-7
					&& DateUtils.compareDateDay(calendar.getTime()) <=0){
				Map<String, Object> map = new HashMap<>();
				map.put("context", getTryVipContext(merchantId, calendar, 0));
				map.put("type", "vip");
				li.add(map);
			}
		}
		List<MoneyChange> moneyList = moneyChangeService.selectListByMoneyTypeAndStutas(merchantId, "10D", "10A");
		if (moneyList !=null && moneyList.size()>0) {
			BigDecimal redMoney = new BigDecimal(0); 
			for (MoneyChange moneyChange : moneyList) {
				redMoney = redMoney.add(moneyChange.getTrxAmt());
			}
			Map<String, Object> map = new HashMap<>();
			map.put("context", "您有"+moneyList.size()+"个红包,共计{"+redMoney.setScale(0, BigDecimal.ROUND_UP)+"}元/n"
					+ "待领取,点击窗口获取红包");
			map.put("type", "redPackage");
			li.add(map);
		}
		return AjaxResult.successAndData("成功", li);
	}



	/**
	 * 获取轮播图 官网
	 *
	 * @param type
	 *
	 * @return
	 */
	@RequestMapping("/officialList")
	@ResponseBody
	public AjaxResult officialList(String type) {
		if (StringUtils.isEmpty(type)) {
			return AjaxResult.error(1, "缺失参数");
		}
		if (StringUtils.equals(type, ResourcesTypeStatus.WSL.getCode())) {
			// 手机
			type = ResourcesTypeStatus.WSL.getCode();
		} else if (StringUtils.equals(type, ResourcesTypeStatus.WZL.getCode())) {
			// PC
			type = ResourcesTypeStatus.WZL.getCode();
		}  else {
			return AjaxResult.error(2, "暂不支持此类型");
		}
		return resourcesDataService.selectResourcesDataByType(type);
	}

	
	/**
	 * 升级核心合伙人权益介绍
	 * 
	 * @param type
	 *
	 * @return
	 */
	@RequestMapping("/equityIntroduce")
	@ResponseBody
	public AjaxResult equityIntroduce() {
		Map<String, String> map = new HashMap<>();
		map.put("upCondition", "充值2000元");
		map.put("upIntroduce", "升级核心合伙人，享最高级别政策，还可享受推广下级核心合伙人所有推广收入");
		map.put("equity",
				"1. 收款 11/万-17/万\n2. 还款 27/万-34/万\n3. 空卡 25/万-40/万\n4. 碰一碰 8/万+2-14/万+2\n5. 下级推荐升级VIP（20-50的管理差价）\n6. 下级推荐升级核心合伙人（150-350的管理差价）\n7. 管理提现（1%-5%收入）\n8. 直推VIP收益199元，间推70元，间间推35元\n9. 直推合伙人800元、间推200元\n10. 推广10个核心合伙人返还升级费用");
		return AjaxResult.successAndData("成功", map);
	}
	/********************************* 待定 ****************************************/
	/**
	 * 获取178学堂 板块名称 描述
	 *
	 * @return
	 */
	@RequestMapping("/list")
	@ResponseBody
	public AjaxResult list() {
		return resourcesTypeService.selectResourcesTypeAllByXT();
	}

	/**
	 * 获取178 资料详情
	 *
	 * @param type
	 * @return
	 */
	@RequestMapping("/data")
	@ResponseBody
	public AjaxResult data(String type) {
		return resourcesDataService.selectResourcesDataByType(type);
	}
	
	
	public String getTryVipContext(String merchantId, Calendar calendar, int type) {
		Map<String, Object> map1 = new HashMap<String, Object>();
		map1.put("orderTypes", "0");
		map1.put("completeTimeEndTime1", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, calendar.getTime()));
		PaymentOrder wkorder = new PaymentOrder();
		wkorder.setMerchantId(merchantId);
		wkorder.setParams(map1);
		wkorder.setOrderStatus(1);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("orderTypes", "1");
		map.put("completeTimeEndTime1", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, calendar.getTime()));
		PaymentOrder ykorder = new PaymentOrder();
		ykorder.setMerchantId(merchantId);
		ykorder.setOrderStatus(1);
		ykorder.setParams(map);
		Map<String, Object> wk = paymentOrderService.selectOrderTotalMoney(wkorder);
		Map<String, Object> yk = paymentOrderService.selectOrderTotalMoney(ykorder);
		BigDecimal wkMoney = new BigDecimal(wk.get("totalMoney") != null ? wk.get("totalMoney").toString() : "0");
		BigDecimal ykMoney = new BigDecimal(yk.get("totalMoney") != null ? yk.get("totalMoney").toString() : "0");
		String rateStr = "";
		try {
			rateStr = RedisPoolUtil.get("rate");
		} catch (Exception e) {
			rateStr = "nil";
		}
		if (rateStr == null || "".equals(rateStr) || "nil".equals(rateStr)) {
			SystemConfig config = configService.selectSystemConfigByConfigCode("rate");
			try {
				RedisPoolUtil.setex("rate", config.getConfigValue(), 86400);
			} catch (Exception e) {
				// TODO: handle exception
			}
			rateStr = config.getConfigValue();
		}
		JSONObject rateJson = JSONObject.parseObject(rateStr);
		BigDecimal wkPro = new BigDecimal(rateJson.getString("wk").split("\\+")[1])
				.subtract(new BigDecimal(rateJson.getString("vipWk").split("\\+")[1]));
		BigDecimal wkRate = new BigDecimal(rateJson.getString("wk").split("\\+")[0])
				.subtract(new BigDecimal(rateJson.getString("vipWk").split("\\+")[0]));
		BigDecimal ykPro = new BigDecimal(rateJson.getString("yk").split("\\+")[1])
				.subtract(new BigDecimal(rateJson.getString("vipYk").split("\\+")[1]));
		BigDecimal ykRate = new BigDecimal(rateJson.getString("yk").split("\\+")[0])
				.subtract(new BigDecimal(rateJson.getString("vipYk").split("\\+")[0]));
		BigDecimal wkMoney1 = wkMoney.multiply(wkRate).add(wkPro).setScale(2, BigDecimal.ROUND_UP);
		BigDecimal ykMoney1 = ykMoney.multiply(ykRate).add(ykPro).setScale(2, BigDecimal.ROUND_UP);
		String context = "";
		if (type == 0) {
			context = "您的免费VIP体验即将到期,截止目前为止，共计产生{" + wkMoney.add(ykMoney).setScale(2, BigDecimal.ROUND_UP)
					+ "}元,已为您节省{" + wkMoney1.add(ykMoney1)+ "}元,升级VIP享永久超低费率,点击当前窗口去升级!";
		} else if (type == 1) {
			context = "您的活动期超低费率已经结束，活动期两个月为您节省{" + wkMoney1.add(ykMoney1)
					+ "}元,升级为VIP终身使用{" + new BigDecimal(rateJson.getString("wk").split("\\+")[0])
							.multiply(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_DOWN)
					+ "}费率,继续使用，预存升级费用除去正常省钱费用外，会以额外消费返佣形式反到后台,点击当前窗口去升级!";
		}
		return context;
	}

}